<template>
    <div class="pet">
        <div class="pcount">您一共有<b>{{ petCount }}</b>个宠物
            <el-button type="success" icon="el-icon-plus" style="margin-left: 10px;" @click="addCustomerPet"></el-button>
        </div>
        <div class="ptable">
            <el-table :data="tableData" style="width: 100%;font-size: 13px;">
                <el-table-column prop="date" label="宠物头像" width="180">
                    <template slot-scope="{ row }">
                        <el-image style="width: auto; height: 40px; border:none;cursor: pointer;" :src="getImage(row.image)"
                            :preview-src-list="[`http://localhost:8081/common/download?name=${row.image}`]">
                            <div slot="error" class="image-slot">
                                <img src="" style="width: auto; height: 40px; border:none;">
                            </div>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="名称" width="180">
                </el-table-column>
                <el-table-column prop="typeName" label="类型">
                </el-table-column>
                <el-table-column prop="age" label="年龄">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <i class="el-icon-edit-outline" style="font-size:20px;" @click="editCustomerPet(scope.row)"></i>
                        <i class="el-icon-delete" style="font-size:20px;margin-left: 5px;"
                            @click="deleteByPetId(scope.row.id)"></i>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog :title="this.form.name == null ? '新增' : '修改'" style="text-align: center;"
            :visible.sync="dialogFormVisible" width="450px">
            <el-form :model="form">
                <el-form-item label="名称" label-width="50px">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="类型" label-width="50px">
                    <el-select v-model="form.typeName" placeholder="请选择" style="width:100%">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="年龄" label-width="50px">
                    <el-input v-model="form.age" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="头像" label-width="50px">
                    <el-upload class="avatar-uploader" action="http://localhost:8081/common/upload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :on-change="onChange" ref="upload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" width="92px" height="92px" />
                        <i v-else class="el-icon-plus avatar-uploader-icon" style="line-height: 6;"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelDialog">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "MyPet",
    data() {
        return {
            petCount: 0,
            tableData: [],
            customer: localStorage.getItem("customer") ? JSON.parse(localStorage.getItem("customer")) : {},
            dialogFormVisible: false,
            form: {},
            imageUrl: '',
            options: [{
                value: '金毛',
                label: '金毛'
            }, {
                value: '拉布拉多',
                label: '拉布拉多'
            }, {
                value: '猫咪',
                label: '猫咪'
            }, {
                value: '二哈',
                label: '二哈'
            }],

        }
    },
    created() {
        this.getPetData()
        // this.count = this.getPetData().length;

    },
    mounted() {
        console.log(this.tableData);
    },
    methods: {
        getImage(image) {
            //图片回显
            return "http://localhost:8081/common/download?name=" + image
        },
        getPetData() {
            //根据用户id获取自己的宠物列表
            var id = JSON.parse(localStorage.getItem("customer")).id
            this.request.get("/pet/byCustomerId/" + id).then(res => {
                if (res.code == 200) {
                    console.log("petList====>", res.data.petList)
                    this.tableData = res.data.petList
                    this.petCount = res.data.count
                }
            })
        },
        addCustomerPet() {
            //打开新增宠物窗口
            this.dialogFormVisible = true;
            this.form = {}
            this.imageUrl = ''
        },
        save() {
            //保存宠物
            this.form.customerId = this.customer.id
            this.request.post("/pet", this.form).then(res => {
                if (res.code == 200) {

                    this.$message.success("修改成功")
                    this.dialogFormVisible = false
                    this.getPetData()
                } else {
                    this.$message.success("修改失败")
                }
            })
        },
        cancelDialog() {
            //关闭弹窗
            this.dialogFormVisible = false
            this.form = {}
            this.imageUrl = ''
        },
        editCustomerPet(row) {
            //打开修改宠物弹窗
            this.dialogFormVisible = true;
            this.form = JSON.parse(JSON.stringify(row))
            this.imageUrl = "http://localhost:8081/common/download?name=" + row.image

        },
        deleteByPetId(id) {
            //删除宠物
            this.$confirm('确认删除吗？', '操作确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    await this.request.delete("/pet/" + id).then(res => {
                        if (res.code == 200) {
                            this.$message.success("删除成功");
                            this.getPetData();
                        } else {
                            this.$message.success("删除失败")
                        }
                    })
                })
                .catch(() => { })
        },
        handleAvatarSuccess(res) {
            this.imageUrl = "http://localhost:8081/common/download?name=" + res.msg//图片回显
            this.form.image = res.msg
            console.log(this.form.image);

        },
        onChange(file) {//校验图片格式 element-ui组件函数 
            if (file) {
                const suffix = file.name.split('.')[1]
                const size = file.size / 1024 / 1024 < 2
                if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
                    this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                    this.$refs.upload.clearFiles()
                    return false
                }
                if (!size) {
                    this.$message.error('上传文件大小不能超过 2MB!')
                    return false
                }
                return file
            }
        },
    }
}
</script>

<style scoped>
.pcount {
    display: block;
    border-bottom: 1px solid #e6e6e6;
    height: 40px;
}

.ptable {}

.pet {}
</style>